﻿package com.example.tourpal.user;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.example.tourpal.R;

public class UserHeadActivity extends Activity {
	public static final String TAG = "chengongguo/UserHeadActivity";
	public static final int HEAD_TYPE_RES = 1;
	public static final int HEAD_TYPE_FILE = 2;
	private TextView mTextViewSelect;
	private TextView mTextViewPicture;
	private TextView mTextViewCapture;
	private TextView mTextViewCancel;

	private String tempFileName;
	private String fileName;

	// private Tools mTools;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_head_view);
		// mTools = new Tools(this, TAG);
		initIntent();
		// initStorageFileManager();
		initContentView();
	}

	private void initIntent() {
		// TODO Auto-generated method stub
		String fileTitle = getIntent().getStringExtra("fileTitle");
		String filePath = Environment.getExternalStorageDirectory()
				+ "/TourPal/";
		checkFolderExists(filePath);
		fileName = filePath + "." + fileTitle + ".png";
		tempFileName = filePath + ".temp.png";
		Log.i(TAG, "fileName=" + fileName);
	}

	// private void initStorageFileManager() {
	// // TODO Auto-generated method stub
	//
	// // tempFileName = Environment.getExternalStorageDirectory()
	// // + "/TourPal/.temp.png";
	// fileName = Environment.getExternalStorageDirectory() + "/." + fileTitle
	// + ".png";
	// tempFileName = Environment.getExternalStorageDirectory()
	// + "/.temp.png";
	// }

	private boolean checkFolderExists(String strFolder) {
		Log.i(TAG, "checkFolderExists() strFolder=" + strFolder);
		File file = new File(strFolder);
		if (!file.exists()) {
			if (file.mkdir()) {
				return true;
			} else
				return false;
		}
		return true;
	}

	private void initContentView() {
		mTextViewSelect = (TextView) findViewById(R.id.user_head_select);
		mTextViewPicture = (TextView) findViewById(R.id.user_head_picture);
		mTextViewCapture = (TextView) findViewById(R.id.user_head_capture);
		mTextViewCancel = (TextView) findViewById(R.id.user_head_cancel);
		mTextViewSelect.setOnClickListener(mOnClickListener);
		mTextViewPicture.setOnClickListener(mOnClickListener);
		mTextViewCapture.setOnClickListener(mOnClickListener);
		mTextViewCancel.setOnClickListener(mOnClickListener);
	}

	private OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.user_head_select:
				goSelectPicture();
				break;
			case R.id.user_head_picture:
				goPicture();
				break;
			case R.id.user_head_capture:
				goCapture();
				break;
			case R.id.user_head_cancel:
				finish();
				break;
			default:
				break;
			}
		}
	};

	private int headRes = 0;

	protected void goSelectPicture() {
		final TypedArray allHeadRes = getResources().obtainTypedArray(
				R.array.person_heads);
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < allHeadRes.length(); i++) {
			Map<String, Object> listItem = new HashMap<String, Object>();
			listItem.put("image", allHeadRes.getResourceId(i, 0));
			listItems.add(listItem);
		}
		View userHeadLayout = getLayoutInflater().inflate(
				R.layout.user_head_select, null);
		GridView userHeads = (GridView) userHeadLayout
				.findViewById(R.id.user_heads);
		final RoundImageView userHead = (RoundImageView) userHeadLayout
				.findViewById(R.id.user_head_selected);
		SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
				R.layout.user_head_select_item, new String[] { "image" },
				new int[] { R.id.user_head });
		userHeads.setAdapter(simpleAdapter);
		userHeads.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				headRes = allHeadRes.getResourceId(position, 0);
				userHead.setImageResource(headRes);
			}
		});
		new AlertDialog.Builder(this)
				.setIcon(R.drawable.ic_launcher)
				.setTitle("请选择头像")
				.setView(userHeadLayout)
				.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = new Intent(TAG);
								intent.putExtra("headType", HEAD_TYPE_RES);
								intent.putExtra("headRes", headRes);
								sendBroadcast(intent);
								finish();
							}

						})
				.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						}).create().show();
	}

	protected void goPicture() {
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, 1);
	}

	protected void goCapture() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(tempFileName)));
		startActivityForResult(intent, 2);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		// 如果是直接从相册获取
		case 1:
			if (data != null)
				startPhotoZoom(data.getData());
			break;
		// 如果是调用相机拍照时
		case 2:
			startPhotoZoom(Uri.fromFile(new File(tempFileName)));
			break;
		// 取得裁剪后的图片
		case 3:
			if (data != null) {
				setPicToView(data);
			}
			break;
		default:
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Log.i(TAG, "startPhotoZoom(" + uri.toString() + ")");
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			savePicture(photo);
		}

	}

	private void savePicture(Bitmap photo) {
		// TODO Auto-generated method stub
		Log.i(TAG, "savePicture()");
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(file);
			photo.compress(Bitmap.CompressFormat.PNG, 80, out);
			out.flush();
			out.close();
			Intent intent = new Intent(TAG);
			intent.putExtra("headType", HEAD_TYPE_FILE);
			intent.putExtra("fileName", fileName);
			sendBroadcast(intent);
			Log.i(TAG, "savePicture success,fileName=" + fileName);
			finish();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}
}